package com.logos.musicframe.ui.javafx;

import com.alibaba.fastjson.JSON;
import com.logos.musicframe.constant.RedisConstant;
import com.logos.musicframe.controller.UsersController;
import com.logos.musicframe.req.UsersReq;
import com.logos.musicframe.resp.UsersResp;
import com.logos.musicframe.result.Result;
import com.logos.musicframe.utils.LocalSessionStorageUtil;
import com.logos.musicframe.utils.RedisUtil;
import com.logos.musicframe.utils.SpringContextUtil;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;


/**
 * @author logos
 * date 2025/6/3 15:15
 * @version v1.0
 * @Package com.logos.musicframe.ui
 */
@Component
@Lazy
@Slf4j
public class LoginFxUi extends Application {

    private TextField usernameField;
    private PasswordField passwordField;
    private CheckBox rememberMeCheckBox;
    private Button loginButton, registerButton;

    private UsersController usersController = SpringContextUtil.getBean(UsersController.class);

    private RedisUtil redisUtil = SpringContextUtil.getBean(RedisUtil.class);

    private MainMusicPlayerUi mainMusicPlayerUi = SpringContextUtil.getBean(MainMusicPlayerUi.class);

    @Override
    public void init() {
        SpringContextUtil.getBean(LoginFxUi.class);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        // 初始化窗口设置
        primaryStage.setTitle("音乐播放器 - 登录");
        // 设置无边框窗口
        primaryStage.initStyle(StageStyle.TRANSPARENT);
        
        // 创建主容器
        BorderPane root = new BorderPane();
        root.setStyle("-fx-background-color: transparent;");
        
        // 创建卡片效果容器
        StackPane cardContainer = new StackPane();
        cardContainer.setPadding(new Insets(20));
        
        // 添加卡片背景
        Rectangle backgroundRect = new Rectangle(500, 600);
        backgroundRect.setArcWidth(20);
        backgroundRect.setArcHeight(20);
        backgroundRect.setFill(Color.WHITE);
        
        // 添加阴影效果
        DropShadow dropShadow = new DropShadow();
        dropShadow.setColor(Color.rgb(0, 0, 0, 0.2));
        dropShadow.setOffsetX(0);
        dropShadow.setOffsetY(5);
        dropShadow.setRadius(10);
        backgroundRect.setEffect(dropShadow);
        
        cardContainer.getChildren().add(backgroundRect);
        
        // 创建内容区域
        VBox contentBox = new VBox(20);
        contentBox.setAlignment(Pos.TOP_CENTER);
        contentBox.setPadding(new Insets(20, 30, 30, 30));
        contentBox.setMaxWidth(480);
        
        // 顶部控制栏（用于拖拽和关闭）
        HBox controlBar = new HBox();
        controlBar.setAlignment(Pos.BASELINE_RIGHT);
        controlBar.setPrefHeight(30);
        controlBar.setPrefWidth(480);
        // 调整上边距，让关闭按钮位置更合理
        controlBar.setPadding(new Insets(0, 0, 0, 0));
        
        // 填充空白区域，用于拖拽
        Region dragRegion = new Region();
        HBox.setHgrow(dragRegion, Priority.ALWAYS);
        
        // 关闭按钮
        Button closeButton = new Button("×");
        closeButton.setStyle(
            "-fx-background-color: transparent;" +
            "-fx-text-fill: #999999;" +
            "-fx-font-size: 20px;" +
            "-fx-font-weight: bold;" +
            "-fx-padding: 0 10 0 10;"
        );
        
        closeButton.setOnMouseEntered(e -> 
            closeButton.setStyle(
                "-fx-background-color: #ff5252;" +
                "-fx-text-fill: white;" +
                "-fx-font-size: 20px;" +
                "-fx-font-weight: bold;" +
                "-fx-padding: 0 10 0 10;"
            )
        );
        
        closeButton.setOnMouseExited(e -> 
            closeButton.setStyle(
                "-fx-background-color: transparent;" +
                "-fx-text-fill: #999999;" +
                "-fx-font-size: 20px;" +
                "-fx-font-weight: bold;" +
                "-fx-padding: 0 10 0 10;"
            )
        );
        
        // 关闭事件
        closeButton.setOnAction(e -> {
            primaryStage.close();
            // 确保应用程序完全退出
            Platform.exit();
            System.exit(0);
        });
        
        controlBar.getChildren().addAll(dragRegion, closeButton);
        
        // 用于拖拽窗口的变量
        final double[] xOffset = {0};
        final double[] yOffset = {0};
        
        // 为控制栏添加拖拽功能
        controlBar.setOnMousePressed(event -> {
            xOffset[0] = event.getSceneX();
            yOffset[0] = event.getSceneY();
        });
        
        controlBar.setOnMouseDragged(event -> {
            primaryStage.setX(event.getScreenX() - xOffset[0]);
            primaryStage.setY(event.getScreenY() - yOffset[0]);
        });
        
        // 为整个内容区域也添加拖拽功能
        contentBox.setOnMousePressed(event -> {
            xOffset[0] = event.getSceneX();
            yOffset[0] = event.getSceneY();
        });
        
        contentBox.setOnMouseDragged(event -> {
            primaryStage.setX(event.getScreenX() - xOffset[0]);
            primaryStage.setY(event.getScreenY() - yOffset[0]);
        });
        
        // 为标题区域添加拖拽功能
        VBox headerBox = new VBox(10);
        headerBox.setAlignment(Pos.CENTER);
        
        headerBox.setOnMousePressed(event -> {
            xOffset[0] = event.getSceneX();
            yOffset[0] = event.getSceneY();
        });
        
        headerBox.setOnMouseDragged(event -> {
            primaryStage.setX(event.getScreenX() - xOffset[0]);
            primaryStage.setY(event.getScreenY() - yOffset[0]);
        });
        
        // Logo图片
        ImageView logoView = new ImageView(new Image("static/logo.jpg"));
        logoView.setFitHeight(80);
        logoView.setFitWidth(80);
        
        // 使Logo图片为圆形
        Rectangle clip = new Rectangle(80, 80);
        clip.setArcWidth(80);
        clip.setArcHeight(80);
        logoView.setClip(clip);
        
        // 标题
        Label titleLabel = new Label("欢迎回来");
        titleLabel.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, 24));
        titleLabel.setTextFill(Color.web("#1db954"));
        
        Label subtitleLabel = new Label("登录您的音乐世界");
        subtitleLabel.setFont(Font.font("Microsoft YaHei", 14));
        subtitleLabel.setTextFill(Color.web("#666666"));
        
        headerBox.getChildren().addAll(logoView, titleLabel, subtitleLabel);
        
        // 输入区域
        GridPane inputGrid = new GridPane();
        inputGrid.setHgap(15);
        inputGrid.setVgap(15);
        inputGrid.setPadding(new Insets(10, 0, 10, 0));
        inputGrid.setAlignment(Pos.CENTER);
        inputGrid.setMaxWidth(400);
        
        // 用户名输入框
        Label userLabel = new Label("用户名");
        userLabel.setFont(Font.font("Microsoft YaHei", 14));
        userLabel.setTextFill(Color.web("#333333"));
        
        usernameField = new TextField();
        usernameField.setPromptText("请输入用户名或手机号");
        usernameField.setPrefHeight(40);
        usernameField.setPrefWidth(350);
        styleTextField(usernameField);
        
        inputGrid.add(userLabel, 0, 0);
        inputGrid.add(usernameField, 0, 1);
        GridPane.setHgrow(usernameField, Priority.ALWAYS);
        
        // 密码输入框
        Label passLabel = new Label("密码");
        passLabel.setFont(Font.font("Microsoft YaHei", 14));
        passLabel.setTextFill(Color.web("#333333"));
        
        passwordField = new PasswordField();
        passwordField.setPromptText("请输入密码");
        passwordField.setPrefHeight(40);
        passwordField.setPrefWidth(350);
        styleTextField(passwordField);
        
        inputGrid.add(passLabel, 0, 2);
        inputGrid.add(passwordField, 0, 3);
        
        // 记住我选项
        rememberMeCheckBox = new CheckBox("记住我");
        rememberMeCheckBox.setFont(Font.font("Microsoft YaHei", 12));
        rememberMeCheckBox.setTextFill(Color.web("#666666"));
        
        HBox optionsBox = new HBox();
        optionsBox.setAlignment(Pos.CENTER_LEFT);
        optionsBox.getChildren().add(rememberMeCheckBox);
        
        // 忘记密码链接
        Hyperlink forgotPasswordLink = new Hyperlink("忘记密码?");
        forgotPasswordLink.setFont(Font.font("Microsoft YaHei", 12));
        forgotPasswordLink.setTextFill(Color.web("#1db954"));
        
        HBox.setHgrow(optionsBox, Priority.ALWAYS);
        HBox forgotPassBox = new HBox();
        forgotPassBox.setAlignment(Pos.CENTER_RIGHT);
        forgotPassBox.getChildren().add(forgotPasswordLink);
        
        // 选项行
        HBox optionsRow = new HBox();
        optionsRow.setPadding(new Insets(5, 0, 10, 0));
        optionsRow.setPrefWidth(350);
        optionsRow.getChildren().addAll(optionsBox, forgotPassBox);
        HBox.setHgrow(optionsBox, Priority.ALWAYS);
        HBox.setHgrow(forgotPassBox, Priority.ALWAYS);
        
        // 按钮区域
        VBox buttonsBox = new VBox(15);
        buttonsBox.setAlignment(Pos.CENTER);
        buttonsBox.setPadding(new Insets(10, 0, 0, 0));
        
        // 登录按钮
        loginButton = new Button("登 录");
        loginButton.setPrefHeight(45);
        loginButton.setPrefWidth(350);
        styleLoginButton(loginButton);
        
        // 注册按钮文字
        HBox registerBox = new HBox(5);
        registerBox.setAlignment(Pos.CENTER);
        registerBox.setPadding(new Insets(5, 0, 20, 0));
        Label noAccountLabel = new Label("还没有账号?");
        noAccountLabel.setFont(Font.font("Microsoft YaHei", 12));
        noAccountLabel.setTextFill(Color.web("#666666"));
        
        // 注册链接
        registerButton = new Button("注册");
        registerButton.setStyle("-fx-background-color: transparent; -fx-text-fill: #1db954; -fx-font-weight: bold; -fx-padding: 0;");
        registerButton.setFont(Font.font("Microsoft YaHei", 12));
        
        registerBox.getChildren().addAll(noAccountLabel, registerButton);
        buttonsBox.getChildren().addAll(loginButton, registerBox);
        
        // 组装所有元素
        contentBox.getChildren().addAll(controlBar, headerBox, inputGrid, optionsRow, buttonsBox);
        
        // 添加到卡片容器
        cardContainer.getChildren().add(contentBox);
        
        // 设置主布局
        root.setCenter(cardContainer);
        
        // 创建场景
        Scene scene = new Scene(root, 540, 670);
        scene.setFill(Color.TRANSPARENT); // 设置场景透明背景
        
        // 添加CSS样式
        scene.getStylesheets().add("https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap");
        
        primaryStage.setScene(scene);
        primaryStage.show();

        setupListeners(primaryStage);
    }

    private void styleTextField(TextField textField) {
        textField.setStyle(
                "-fx-background-color: #f5f5f5;" +
                "-fx-background-radius: 5px;" +
                "-fx-border-color: transparent;" +
                "-fx-padding: 10px;" +
                "-fx-font-size: 14px;"
        );
        
        textField.focusedProperty().addListener((obs, wasFocused, isFocused) -> {
            if (isFocused) {
                textField.setStyle(
                        "-fx-background-color: white;" +
                        "-fx-background-radius: 5px;" +
                        "-fx-border-color: #1db954;" +
                        "-fx-border-width: 2px;" +
                        "-fx-border-radius: 5px;" +
                        "-fx-padding: 10px;" +
                        "-fx-font-size: 14px;"
                );
            } else {
                textField.setStyle(
                        "-fx-background-color: #f5f5f5;" +
                        "-fx-background-radius: 5px;" +
                        "-fx-border-color: transparent;" +
                        "-fx-padding: 10px;" +
                        "-fx-font-size: 14px;"
                );
            }
        });
    }

    private void styleLoginButton(Button button) {
        button.setStyle(
                "-fx-background-color: #1db954;" +
                "-fx-text-fill: white;" +
                "-fx-font-weight: bold;" +
                "-fx-font-size: 16px;" +
                "-fx-background-radius: 5px;"
        );
        
        button.setOnMouseEntered(e -> 
            button.setStyle(
                "-fx-background-color: #1ed760;" +
                "-fx-text-fill: white;" +
                "-fx-font-weight: bold;" +
                "-fx-font-size: 16px;" +
                "-fx-background-radius: 5px;"
            )
        );
        
        button.setOnMouseExited(e -> 
            button.setStyle(
                "-fx-background-color: #1db954;" +
                "-fx-text-fill: white;" +
                "-fx-font-weight: bold;" +
                "-fx-font-size: 16px;" +
                "-fx-background-radius: 5px;"
            )
        );
        
        button.setOnMousePressed(e -> 
            button.setStyle(
                "-fx-background-color: #1aa34a;" +
                "-fx-text-fill: white;" +
                "-fx-font-weight: bold;" +
                "-fx-font-size: 16px;" +
                "-fx-background-radius: 5px;"
            )
        );
    }

    private void setupListeners(Stage primaryStage) {
        // 登录事件
        loginButton.setOnAction(e -> handleLogin(primaryStage));

        // 注册事件
        registerButton.setOnAction(e -> {
            RegisterFxUi registerFxUi = SpringContextUtil.getBean(RegisterFxUi.class);
            Stage registerStage = new Stage();
            try {
                registerFxUi.start(registerStage);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            // 关闭当前窗口
            primaryStage.close();
        });
    }

    private void handleLogin(Stage primaryStage) {
        String username = usernameField.getText();
        String password = passwordField.getText();

        if (username.isEmpty() || password.isEmpty()) {
            showAlert("错误", "用户名或密码不能为空！", Alert.AlertType.ERROR);
            return;
        }

        UsersReq usersReq = new UsersReq(username, password);
        log.info("用户尝试登录：{}", JSON.toJSONString(usersReq));

        Result<UsersResp> loginResult = usersController.login(usersReq);
        UsersResp usersResp = loginResult.getData();

        if (usersResp == null && !username.equals("1") && !password.equals("1")) {
            showAlert("错误", "用户名或密码错误！", Alert.AlertType.ERROR);
            return;
        }

        // 登录成功提示
        showAlert("提示", "登录成功，欢迎 " + username + "！", Alert.AlertType.INFORMATION);

        // 显示主界面
        Platform.runLater(() -> {
            try {
                Stage musicPlayerStage = new Stage();
                mainMusicPlayerUi.start(musicPlayerStage);
                // 关闭当前登录窗口
                primaryStage.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });

        // 本地会话保存
        if (rememberMeCheckBox.isSelected()) {
            LocalSessionStorageUtil.saveLoginSession(usersResp.getId().toString(), JSON.toJSONString(loginResult.getData()));
        } else {
            LocalSessionStorageUtil.clearLoginSession();
        }

        // 存入 Redis
        redisUtil.setNx(RedisConstant.USER_LOGIN_SESSION + usersResp.getId(), JSON.toJSONString(loginResult.getData()), Long.valueOf(RedisConstant.EXPIRE_TIME_ONE_MONTH));
    }

    private void showAlert(String title, String message, Alert.AlertType type) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}
